﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace HTComics.Data.Tools
{
    public partial class ImportForm : Form
    {
        string _dataFile;
        string connString = "Data Source=localhost;Initial Catalog=HTCDB;User Id=sa;Password=7Nation!;";
        DataInserter inserter;
        int secs = 0;
        DataTable dtData;
        int total = 0;
        int done = 0;
        int failed = 0;

        public ImportForm()
        {
            InitializeComponent();
        }

        private void btnSelectFile_Click(object sender, EventArgs e)
        {
            Reset();

            if (dlgSelectFile.ShowDialog() == DialogResult.OK)
            {
                txtFileName.Text = dlgSelectFile.FileName;

                if (Path.GetExtension(dlgSelectFile.FileName).ToLower() != ".txt")
                {
                    MessageBox.Show("Only text files allowed", ":: HTC :: Import Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                _dataFile = dlgSelectFile.FileName;                

                List<string> errors;
                dtData = DataImporter.ImportData(connString, _dataFile, out errors);
                if (errors.Count > 0)
                {
                    for (int i = 0; i <= errors.Count - 1; i++)
                    {
                        txtOutput.Text += errors[i] + "\n";
                    }

                    MessageBox.Show("There are errors in the file you have selected, please review the output, fix the errors and try again,", ":: HTC :: Import Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                    return;
                }

                DialogResult res = MessageBox.Show("Are you sure you want to initiate the upload process? Changes cannot be undone.", ":: HTC :: Import Error", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information);
                if (res == System.Windows.Forms.DialogResult.Yes)
                {
                    total = dtData.Rows.Count;

                    tmrTime.Enabled = true;
                    tmrInsert.Enabled = true;
                }
            }
        }

        private void ImportForm_Load(object sender, EventArgs e)
        {
            inserter = new DataInserter(connString);
        }

        private void tmrTime_Tick(object sender, EventArgs e)
        {
            TimeSpan t = TimeSpan.FromSeconds(++secs);

            string time = string.Format("{0:D2}h {1:D2}m {2:D2}s",
                                    t.Hours,
                                    t.Minutes,
                                    t.Seconds);

            lblTime.Text = "Time Elapsed: " + time;
            Application.DoEvents();
        }

        private void Reset()
        {
            dlgSelectFile.Filter = "Text files (*.txt)|";
            txtFileName.Text = "";
            txtOutput.Text = "";
            lblCount.Text = "";

            secs = 0;
            lblTime.Text = "";
            tmrTime.Enabled = false;
        }

        private void tmrInsert_Tick(object sender, EventArgs e)
        {
            tmrInsert.Enabled = false;

            if (dtData.Rows.Count > 0)
            {
                DataRow row = dtData.Rows[0];
                string query = "";

                try
                {
                    inserter.InsertRow(row, out query);
                    lblCount.Text = "Count: " + (++done) + " \\ " + total;
                    progressBar1.Value = done * 100 / total;
                    Application.DoEvents();
                }
                catch (Exception ex)
                {
                    txtOutput.Text += "------------------Insertion Failed -----------------------\n";
                    txtOutput.Text += "Message: " + ex.Message + "\n\n";
                    txtOutput.Text += "Query: " + query + "\n\n";
                    txtOutput.Text += "----------------------------------------------------------\n\n";

                    lblFailed.Text = "Failed: " + (++failed);
                }
                finally
                {
                    row.Delete();
                    tmrInsert.Enabled = true;
                }
            }
            else
            {
                tmrTime.Enabled = false;
                MessageBox.Show("Data uploaded into the system. With " + failed + " failed records./ Please review the output for the failure reason", ":: HTC :: Import Error", MessageBoxButtons.OK, MessageBoxIcon.Information);                
            }
        }
    }
}
